<template>
  <div class="positioning">
    <my-input
      @changeKey="changeKey"
      @viewdetails="viewDetails"
      :isShowSelect="isShowSelect"
      :mountainList="mountainList"
    ></my-input>
    <div id="allmap" class="allmap"></div>

    <van-overlay :show="showDetails" @click="showDetails = false">
      <div class="wrapper">
        <div class="block">地图详情</div>
      </div>
    </van-overlay>
  </div>
</template>

<script>
import MyInput from "./child/Input.vue";
import { getAllLocation, searchMountain, getDetail } from "api/positioning";
import { getSignPackage } from "api/home";

export default {
  name: "Positioning",
  components: {
    MyInput,
  },
  data() {
    return {
      // 初始化坐标
      ggPoint: null,
      // x: 117.071470317,
      // y: 36.600423896,
      longitude: null,
      latitude:  null,
      translateCallback: null,
      showDetails: false,
      // 所有坐标
      Locations: "",
      // 搜索关键字
      searchKeyword: "",
      // 根据关键字获取山体
      mountainList: [],
      // 是否显示选择框
      isShowSelect: false,
      // 选择山体的详情坐标
      selectDetails: {},
      winUrl: "",
      init_key: true,
    };
  },
  mounted() {
    // this.fn()
    this.gotoMap();
    
  },
  methods: {
    gotoMap() {
      this.winUrl = location.href;
      getSignPackage(this.winUrl).then((res) => {
        let that = this;
        if (res.code == 200) {
          // 配置 JS-SDK
          that.wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: res.data.signPackage.appId, // 必填，公众号的唯一标识
            timestamp: res.data.signPackage.timestamp, // 必填，生成签名的时间戳
            nonceStr: res.data.signPackage.nonceStr, // 必填，生成签名的随机串
            signature: res.data.signPackage.signature, // 必填，签名
            jsApiList: ["scanQRCode", "getLocation"], // 必填，需要使用的JS接口列表
          });
          that.wx.ready(() => {
            that.wx.getLocation({
              type: "gcj02",
              success: function (res) {
                // latitude;  纬度，浮点数，范围为90 ~ -90
                // longitude;  经度，浮点数，范围为180 ~ -180。
                let lat = res.latitude;
                let lng = res.longitude;
                let x_PI = (3.14159265358979324 * 3000.0) / 180.0;
                let z =
                  Math.sqrt(lng * lng + lat * lat) +
                  0.00002 * Math.sin(lat * x_PI);
                let theta =
                  Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
                that.longitude = z * Math.cos(theta) + 0.0065;
                that.latitude = z * Math.sin(theta) + 0.006;
                if (that.latitude != null && that.init_key) {
                  that.fn();
                  that.init_key = false;
                }
              },
            });
          });
        }
      });
    },
    fn(item = "") { 
      let that = this;
      // 百度地图API功能
      let map = new BMap.Map("allmap", { enableMapClick: false });
      map.centerAndZoom(new BMap.Point(this.longitude, this.latitude), 13);
      var opts = {
        width: 400, // 信息窗口宽度
        height: 420, // 信息窗口高度
        title: "山体信息", // 信息窗口标题
        enableMessage: true, //设置允许信息窗发送短息
      };
      //添加地图类型控件
      map.addControl(
        new BMap.MapTypeControl({
          mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP],
        })
      );
      map.setCurrentCity("山东"); // 设置地图显示的城市 此项是必须设置的
      map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放

      // 获取所有坐标
      if (!item) {
        getAllLocation().then((res) => {
          if (res.code == 200) {
            that.Locations = res.data;
            for (var i = 0; i < that.Locations.length; i++) {
              var marker = new BMap.Marker(
                new BMap.Point(
                  that.Locations[i].longitude,
                  that.Locations[i].latitude
                )
              );
              if (that.Locations[i].image) {
                // 创建标注 .
                var content = `<div id="sadsasdsad">   
             <h4 style='margin:0 0 5px 0;padding:0.2em 0; font-size: .3rem'>${that.Locations[i].mountain_name}
             (${that.Locations[i].area})</h4> 
             <img style='float:right;margin:4px' id='imgDemo' src='${res.data[i].image} 'width='139' height='104' title='${that.Locations[i].mountain_name}'/>   
             <p style='margin:0;line-height:1.5;font-size: .3rem;text-indent:2em'>${that.Locations[i].location}</p>  
             <div  style="font-size: .3rem;  text-align:center; border: 1px solid #999; width: 2rem; height: 1.2rem; line-height: 1.2rem">点击前往</div>  
             </div>`;
              } else {
                // 创建标注 .
                var content = `<div id="sadsasdsad">   
             <h4 style='margin:0 0 5px 0;padding:0.2em 0'>${that.Locations[i].mountain_name}(${that.Locations[i].area})</h4> 
            
             <p style='margin:0;line-height:1.5;font-size: .3rem;text-indent:2em'>${that.Locations[i].location}</p>  
             <div  style="font-size: .3rem; float:right; text-align:center; border: 1px solid #999; width: 2rem; height: 1.2rem; line-height: 1.2rem; margin: 1rem;">点击前往</div> 
             </div>`;
              }
              map.addOverlay(marker); // 将标注添加到地图中
              addClickHandler(content, marker);
            }
          }
        });
      } else {
        // that.x = item.longitude;
        // that.y = item.latitude;
        map.centerAndZoom(new BMap.Point(item.longitude, item.latitude), 13);
        var marker = new BMap.Marker(
          new BMap.Point(item.longitude, item.latitude)
        );
        if (item.image) {
          // 创建标注 .
          var content = `<div id="sadsasdsad">   
             <h4 style='margin:0 0 5px 0; padding:0.2em 0 font-size: .3rem'>${item.mountain_name}(${item.area})</h4> 
             <img style='float:right;margin:4px' id='imgDemo' src='${item.image} 'width='139' height='104' title='${item.mountain_name}'/>   
             <p style='margin:0;line-height:1.5;font-size: .3rem;text-indent:2em'>${item.location}</p>  
              <div   style="font-size: .3rem;  text-align:center; border: 1px solid #999; width: 2rem; height: 1.2rem; line-height: 1.2rem">点击前往</div>  
             </div>`;
        } else {
          // 创建标注 .
          var content = `<div id="sadsasdsad">   
             <h4 style='margin:0 0 5px 0;padding:0.2em 0; font-size: .3rem' >${item.mountain_name}(${item.area})</h4> 
             <div    style="font-size: .3rem; float:right; text-align:center; border: 1px solid #999; width: 2rem; height: 1.2rem; line-height: 1.2rem; margin: 1rem;">点击前往</div> 
             <p style='margin:0;line-height:1.5;font-size: .3rem;text-indent:2em'>${item.location}</p>  
             </div>`;
        }
        map.addOverlay(marker); // 将标注添加到地图中
        addClickHandler(content, marker);
      }

      function addClickHandler(content, marker) {
        marker.addEventListener("click", function (e) {
          openInfo(content, e); 
          getDetail(e.target.point.lng,e.target.point.lat).then(res => {
              console.log(res.data);
              if(res.code == 200){
                setTimeout(() => {
                  document.getElementById("sadsasdsad").onclick = () => {
                    that.gotoMap();
                    window.location.href = `http://api.map.baidu.com/direction?origin=latlng:${that.latitude},${that.longitude}|name:我的位置&destination=${res.data.mountain_name}&mode=driving&region=济南&output=html&src=webapp.baidu.openAPIdemo`;
                  };
                }, 500);
              }
          }) 
        });
      }
      function openInfo(content, e) {
        var p = e.target;
        var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
        var infoWindow = new BMap.InfoWindow(content, opts); // 创建信息窗口对象
        map.openInfoWindow(infoWindow, point); //开启信息窗口

        // window.location.href = 'http://api.map.baidu.com/direction?origin=latlng:34.264642646862,108.95108518068|name:我家&destination=大雁塔&mode=driving&region=西安&output=html&src=webapp.baidu.openAPIdemo'
      }
    },
    changeKey(info) {
      this.isShowSelect = true;
      if (info == "") {
        this.isShowSelect = false;
      } else {
        searchMountain(info).then((res) => {
          if (res.code == 200) {
            this.mountainList = res.data;
          } else {
            this.mountainList = [];
          }
        });
      }
    },
    viewDetails(item) {
      this.selectDetails = item;
      this.isShowSelect = false;
      this.Locations = [];
      this.fn(item);
    },
  },
  beforeRouteEnter(to, from, next) {
    let u = navigator.userAgent;
    let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    // XXX: 修复iOS版微信HTML5 History兼容性问题 
    if (isiOS && to.path !== location.pathname) { 
      // 此处不可使用location.replace
      location.replace(to.fullPath);
    } else {
      next();
    }
  },
  // watch:{
  //    'Locations': function(){
  //     //  this.fn()
  //    }
  // }
};
</script>

<style lang="less" scoped>
.positioning {
  .allmap {
    padding-top: 10px;
    width: 100vw;
    height: 100vh;
  }
  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .block {
    margin: 0 40px;
    padding: 10px;
    width: 100%;
    height: 300px;
    border-radius: 10px;
    background-color: #fff;
  }
}
</style>